/******************************************************************************
 * Copyright (C) 2013 ShenZhen ComTop Information Technology Co.,Ltd
 * All Rights Reserved.
 * 本软件为深圳康拓普开发研制。未经本公司正式书面同意，其他任何个人、团体
 * 不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package com.code.common.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * 网络信息工具类
 * <pre>
 * 提供获取服务端和客户端网络信息的工具方法
 * </pre>
 * @author 陈星凌
 * @since TOP4.0
 * @version 2013-1-30 陈星凌 由最小系统迁移， 由NetUtil改名为NetInfoUtil
 */
public class NetInfoUtil {
	/**
	 * 获得客户端IP
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return 客户端IP
	 */
	public static String getRemoteAddr(HttpServletRequest request) {
		String remoteAddrIP = request.getHeader("x-forwarded-for");
		if (remoteAddrIP == null || remoteAddrIP.length() == 0
				|| "unknown".equalsIgnoreCase(remoteAddrIP)) {
			remoteAddrIP = request.getHeader("Proxy-Client-IP");
		}
		if (remoteAddrIP == null || remoteAddrIP.length() == 0
				|| "unknown".equalsIgnoreCase(remoteAddrIP)) {
			remoteAddrIP = request.getHeader("WL-Proxy-Client-IP");
		}
		if (remoteAddrIP == null || remoteAddrIP.length() == 0
				|| "unknown".equalsIgnoreCase(remoteAddrIP)) {
			remoteAddrIP = request.getHeader("HTTP_CLIENT_IP");
		}
		if (remoteAddrIP == null || remoteAddrIP.length() == 0
				|| "unknown".equalsIgnoreCase(remoteAddrIP)) {
			remoteAddrIP = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (remoteAddrIP == null || remoteAddrIP.length() == 0
				|| "unknown".equalsIgnoreCase(remoteAddrIP)) {
			remoteAddrIP = request.getRemoteAddr();
		}

		return remoteAddrIP;
	}

	/**
	 * 获得本地服务端IP
	 * 
	 * @return 本地服务端IP
	 * @throws UnknownHostException 未知主机地址异常
	 */
	public static String getLocalAddr() throws UnknownHostException {
		InetAddress addr = InetAddress.getLocalHost();
		return addr.getHostAddress();
	}

	/**
	 * 获得服务端主机名称
	 * 
	 * @return 本地服务端IP
	 * @throws UnknownHostException 未知主机地址异常
	 */
	public static String getServerName() throws UnknownHostException {
		InetAddress addr = InetAddress.getLocalHost();
		return addr.getHostName();
	}
}